package com.itheima.wisdomnext.service.ImpI;

import com.itheima.wisdomnext.Handler.WebSocketHandler;
import com.itheima.wisdomnext.entity.Message;
import com.itheima.wisdomnext.entity.ReportReplyTemplate;
import com.itheima.wisdomnext.entity.Result.enumcalss.ErrorCode;
import com.itheima.wisdomnext.entity.Users;
import com.itheima.wisdomnext.mapper.MessageMapper;
import com.itheima.wisdomnext.mapper.UserMapper;
import com.itheima.wisdomnext.service.MessageService;
import com.itheima.wisdomnext.util.MessageS_Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息管理服务实现类
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebSocketHandler webSocketHandler;

    // 图片上传存储路径
    private static final String UPLOAD_DIR = "uploads/messages/";

    @Override
    public Map<String, Map<String, Object>> getMessagesGroupedByUser(Integer userId) {
        // 获取该用户相关的所有消息
        List<Message> messages = messageMapper.findMessagesByUserId(userId);
        Map<String, Map<String, Object>> groupedMessages = new HashMap<>();

        for (Message message : messages) {
            Integer senderId = message.getUserId();
            Integer recipientId = message.getRecipientId();
            Integer adminId = message.getAdminId();

            String chatKey;

            // 查询 sender 用户信息
            List<Users> senderList = userMapper.getUserByIdPost(senderId);
            message.setUsers(senderList);

            // 查询 recipient 用户信息（如果有）
            List<Users> recipientList = null;
            if (recipientId != null) {
                recipientList = userMapper.getUserByIdPost(recipientId);
            }
            message.setRecipien(recipientList);

            // 归类逻辑
            if (adminId != null) {
                chatKey = "admin";
            } else if (recipientId != null) {
                chatKey = senderId.equals(userId) ? recipientId.toString() : senderId.toString();
            } else {
                chatKey = "admin";
            }

            // 获取发送者和接收者的姓名
            String senderName = senderList.isEmpty() ? "管理员" : senderList.get(0).getNickname();
            String recipientName = (recipientList != null && !recipientList.isEmpty()) ? recipientList.get(0).getNickname() : "管理员";

            // 添加消息到对应的 chatKey 中
            groupedMessages.computeIfAbsent(chatKey, k -> new HashMap<>());
            Map<String, Object> userMessages = groupedMessages.get(chatKey);

            // 如果 userMessages 中没有对应的 name，先加上 name
            if (!userMessages.containsKey("name")) {
                userMessages.put("name", senderId.equals(userId) ? recipientName : senderName);
            }

            // 添加消息
            List<Message> userMessageList = (List<Message>) userMessages.getOrDefault("messages", new ArrayList<>());
            userMessageList.add(message);
            userMessages.put("messages", userMessageList);
        }

        return groupedMessages;
    }

    @Override
    public Map<String, Map<String, Object>> getMessagesGroupedByAdmin(Integer adminId) {
        List<Message> messages = messageMapper.findMessagesByAdminId(adminId);
        Map<String, Map<String, Object>> groupedMessages = new HashMap<>();

        for (Message message : messages) {
            Integer senderId = message.getUserId();
            Integer recipientId = message.getRecipientId();

            // 查询发送者信息
            List<Users> senderList = userMapper.getUserByIdPost(senderId);
            message.setUsers(senderList);

            // 查询接收者信息
            List<Users> recipientList = null;
            if (recipientId != null) {
                recipientList = userMapper.getUserByIdPost(recipientId);
            }
            message.setRecipien(recipientList);

            // 用 userId 作为 key
            String chatKey = senderId != null ? senderId.toString() : (recipientId != null ? recipientId.toString() : "未知");

            // 获取发送者和接收者昵称
            String senderName = senderList.isEmpty() ? "用户" : senderList.get(0).getNickname();
            String recipientName = (recipientList != null && !recipientList.isEmpty()) ? recipientList.get(0).getNickname() : "用户";

            groupedMessages.computeIfAbsent(chatKey, k -> new HashMap<>());
            Map<String, Object> userMessages = groupedMessages.get(chatKey);

            if (!userMessages.containsKey("name")) {
                userMessages.put("name", senderId.equals(adminId) ? recipientName : senderName);
            }

            List<Message> userMessageList = (List<Message>) userMessages.getOrDefault("messages", new ArrayList<>());
            userMessageList.add(message);
            userMessages.put("messages", userMessageList);
        }

        return groupedMessages;
    }


    @Override
    public void sendMessage(Message message) {
        messageMapper.insertMessage(message);
//        message.setName(userMapper.getUserById(message.getUserId()).getNickname());
        // 主动分发消息
        WebSocketHandler.dispatchMessage(message); // 👈 调用你刚提取出来的公共方法
    }

    /**
     * 上传第一张图片
     * @param files 上传的文件数组
     * @return 图片URL
     */
    private String uploadFirstFile(MultipartFile[] files) {
        if (files == null || files.length == 0) return "";

        MultipartFile firstFile = files[0];
        String fileUrl = "";

        try {
            // 创建存储目录
            File directory = new File(UPLOAD_DIR);
            if (!directory.exists()) directory.mkdirs();

            // 生成新文件名
            String originalFilename = firstFile.getOriginalFilename();
            String newFilename = System.currentTimeMillis() + "_" + originalFilename;
            Path path = Paths.get(UPLOAD_DIR + newFilename);
            Files.copy(firstFile.getInputStream(), path);

            fileUrl = "/uploads/messages/" + newFilename;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileUrl;
    }

    @Override
    public void markMessageAsRead(Integer messageId) {
        messageMapper.markAsRead(messageId);
    }

    @Override
    public List<ReportReplyTemplate> getAllReportReplyTemplates() {
        List<ReportReplyTemplate> allReportReplyTemplates = messageMapper.getAllReportReplyTemplates();
        if (allReportReplyTemplates == null && allReportReplyTemplates.isEmpty()) {
            MessageS_Util.isTrue(true, ErrorCode.FAILED,"获取所有举报回复消息模板失败");
        }
        return allReportReplyTemplates;
    }
}
